import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
	  _username: '',
	  _fullname: '',
	  _logined: false,
	  _token: ''
  }),
  getters: {
	  isLogined: (state) => state._logined,
	  fullname: (state) => state._fullname,
	  token: (state) => state._token
  },
  actions: {
	  async initUserData() {
		  // console.log('initUserData')
		  try {
			  // 异步读取
			  uni.getStorage({
				  key: 'user_info',
				  success: (res) => {
					  // console.log('用户信息:', res.data);
					  this._username = res.data.username
					  this._fullname = res.data.fullname
					  this._logined = res.data.token.length > 0
					  this._token = res.data.token
					  // console.log(this._logined, this._token)
				  }
			  });
		  } catch (error) {
			  console.error('Error initializing user data:', error);
		  }
	  },
	  login(payload) {
		  this._username = payload.username
		  this._fullname = payload.fullName
		  this._logined = true
		  this._token = payload.token

		  // 存储对象
		  const userInfo = {
			  username: payload.username,
			  fullname: payload.fullName,
			  token: payload.token
		  };
		  uni.setStorageSync('user_info', userInfo);
	  },
	  logout() {
		  this._username = ''
		  this._fullname = ''
		  this._logined = false
		  this._token = ''
		  // 存储对象
		  const userInfo = {
		  			  username: '',
		  			  fullname: '',
		  			  token: ''
		  };
		  uni.setStorageSync('user_info', userInfo);
		  uni.removeStorageSync('cookie');
	  },
  },
})

